﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XMK.Framework.DataAccess;
using XMK.Framework.Model;
using System.Data;
using XMK.Utils;

namespace XMK.Framework.Data
{
    public class SqlData
    {
        private static readonly string psql = @"SELECT  s.name pcname,s.create_date,s.modify_date
                        FROM  sys.objects s                       
                         WHERE   s.type IN ( N'P', N'PC' )
                         order by s.modify_date desc";


        private static readonly string sql = @"SELECT  s.name pcname,
	                            replace(c.name,'@','') paraname,
		                        t.name typename,
		                        c.length collength,
		                        c.isoutparam,
		                        c.isnullable		 
                        FROM  sys.objects s
                        inner join syscolumns c on s.object_id = c.id
                        inner join systypes t on c.xtype = t.xtype and t.status = 0
                         WHERE   s.type IN ( N'P', N'PC' )
                            and s.name = '{0}'
                         order by s.name,c.colorder";

        public static List<ProcInfo> GetProcInfos(DbProvider dbProvider)
        {
            DbCmdHelper cmd = new DbCmdHelper(dbProvider, psql);
            cmd.DbCmdInfo.CommandType = CommandType.Text;
            List<ProcInfo> list = DbManager.GetInfoList<ProcInfo>(cmd,
                delegate(out ProcInfo info, DataRow dr)
                {
                    info = new ProcInfo();
                    info.ProcName = ParseHelper.Parse<string>(dr["pcname"]);
                    info.CreateTime = ParseHelper.Parse<DateTime>(dr["create_date"]);
                    info.ModifyTime = ParseHelper.Parse<DateTime>(dr["modify_date"]);
                });
            return list;
        }

        public static List<ProcParaInfo> GetProcParaInfos(DbProvider dbProvider, string procname)
        {
            DbCmdHelper cmd = new DbCmdHelper(dbProvider, string.Format(sql, procname));
            cmd.DbCmdInfo.CommandType = CommandType.Text;
            List<ProcParaInfo> list = DbManager.GetInfoList<ProcParaInfo>(cmd,
                delegate(out ProcParaInfo info, DataRow dr)
                {
                    info = new ProcParaInfo();
                    info.ParaName = ParseHelper.Parse<string>(dr["paraname"]);
                    info.TypeName = ParseHelper.Parse<string>(dr["typename"]);
                    info.ColLength = ParseHelper.Parse<int>(dr["collength"]);
                    info.IsOutParam = ParseHelper.Parse<bool>(dr["isoutparam"]);
                    info.IsNullable = ParseHelper.Parse<bool>(dr["isnullable"]);
                });
            return list;
        }
    }
}
